package com.chrray.position.service.position.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chrray.position.auth.Authentication;
import com.chrray.position.auth.AuthenticationContext;
import com.chrray.position.domain.*;
import com.chrray.position.domain.dto.*;
import com.chrray.position.domain.dto.search.FdUserSearch;
import com.chrray.position.domain.vo.FdAuthEnterpriseVO;
import com.chrray.position.domain.vo.FdAuthPersonalVO;
import com.chrray.position.domain.vo.FdUserResumeVO;
import com.chrray.position.domain.vo.FdUserVO;
import com.chrray.position.enums.YesNoEnum;
import com.chrray.position.exception.ServiceException;
import com.chrray.position.mapper.position.FdUserMapper;
import com.chrray.position.service.position.*;
import lombok.AllArgsConstructor;
import org.apache.commons.math3.util.Pair;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 业务系统用户 接口实现类
 *
 * @author wusiwee
 * @email wusiwee@163.com
 * @since 1.0.1 2024-08-07
 */
@Service
@AllArgsConstructor
public class FdUserServiceImpl extends ServiceImpl<FdUserMapper, FdUser> implements FdUserService {

    @Override
    public void updateLocation(LocationDTO location) {
        FdUser user = FdUser.getCurrentUser();
        user.setCurrentLat(location.getLat());
        user.setCurrentLon(location.getLon());
        updateById(user);
    }

    /**
     * 更新个人信息
     */
    @Override
    public void updateInformation(FdUserInformationDTO info) {
        FdUser user = FdUser.getCurrentUser();
        user.setWxAvatar(info.getWxAvatar());
        user.setName(info.getName());
        user.setPhone(info.getPhone());
        user.setGender(info.getGender());
        user.setBirthYear(info.getBirthYear());
        user.setEduState(info.getEduState());
        user.setEduLevel(info.getEduLevel());
        user.setWorkYears(info.getWorkYears());
        user.setHeight(info.getHeight());
        user.setWeight(info.getWeight());
        user.setRemark(info.getRemark());
        user.setMail(info.getMail());
        user.setUpdateTime(new Date());
        updateById(user);
    }

    /**
     * 更新求职意向
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public FdJobIntentionsDTO updateIntention(FdJobIntentionsDTO intention) {
        FdUser user = FdUser.getCurrentUser();
        FdJobIntentions entity = null;
        if(intention.getId()  == null) {
            entity = new FdJobIntentions();
            BeanUtils.copyProperties(intention, entity);
            if(intention.getExpectedSalary() != null) {
                Pair<Integer, Integer> salaryRange = intention.getExpectedSalary().getSalaryRange();
                entity.setExpectedSalaryStart(salaryRange.getFirst());
                entity.setExpectedSalaryEnd(salaryRange.getSecond());
            }
            entity.setUserId(user.getId());
            entity.setDelFlag(YesNoEnum.NO.getCode());
            entity.setCreateTime(new Date());
            entity.insert();
        } else {
            entity = FdJobIntentions.findOneById(intention.getId());
            BeanUtils.copyProperties(intention, entity);
            if(intention.getExpectedSalary() != null) {
                Pair<Integer, Integer> salaryRange = intention.getExpectedSalary().getSalaryRange();
                entity.setExpectedSalaryStart(salaryRange.getFirst());
                entity.setExpectedSalaryEnd(salaryRange.getSecond());
            }
            entity.updateById();
        }

        // user position rel
        List<Long> expectedPosition = intention.getExpectedPosition();
        FdUserPositionRel.resetRel(entity, expectedPosition);
        intention.setId(entity.getId());
        return intention;
    }

    /**
     * 更新教育经历
     */
    @Override
    public FdEduExperienceDTO updateEduExp(FdEduExperienceDTO body) {
        if (body.getId() == null){
            // 主键为空
            Authentication context = AuthenticationContext.context();
            FdEduExperience entity = new FdEduExperience();
            entity.setUserId(context.getUserId());
            entity.setDelFlag(YesNoEnum.NO.getCode());
            entity.setCreateTime(new Date());
            BeanUtils.copyProperties(body,entity);
            // 新增
            entity.insert();
            body.setId(entity.getId());
        }else {
            // 主键不为空
            FdEduExperience entity = new FdEduExperience().selectById(body.getId());
            BeanUtils.copyProperties(body,entity);
            // 更新
            entity.updateById();
        }
        return body;
    }

    /**
     * 删除教育经历
     */
    @Override
    public Boolean deleteEduExp(Long id) {
        FdEduExperience entity = new FdEduExperience().selectById(id);
        if(entity == null) {
            throw new ServiceException("教育经历不存在");
        }
        //entity.setDelFlag(YesNoEnum.YES.getValue());
        return entity.deleteById();
    }

    /**
     * 更新工作经历
     */
    @Override
    public FdWorkExperienceDTO updateWorkExp(FdWorkExperienceDTO body) {
        if (body.getId() == null){
            // 主键为空
            Authentication context = AuthenticationContext.context();
            FdWorkExperience entity = new FdWorkExperience();
            BeanUtils.copyProperties(body,entity);
            entity.setUserId(context.getUserId());
            entity.setDelFlag(YesNoEnum.NO.getCode());
            entity.setCreateTime(new Date());
            // 新增
            entity.insert();
            body.setId(entity.getId());
        }else {
            // 主键不为空
            FdWorkExperience entity = new FdWorkExperience().selectById(body.getId());
            BeanUtils.copyProperties(body,entity);
            // 更新
            entity.updateById();
        }
        return body;

    }

    /**
     * 删除工作经历
     */
    @Override
    public Boolean deleteWorkExp(Long id) {
        FdWorkExperience entity = new FdWorkExperience().selectById(id);
        if(entity == null) {
            throw new ServiceException("工作经历不存在");
        }
        //entity.setDelFlag(YesNoEnum.YES.getValue());
        return entity.deleteById();
    }

    /**
     * 更新证书
     */
    @Override
    public FdUserCertDTO updateCertificate(FdUserCertDTO body) {
        if (body.getId() == null){
            // 主键为空
            Authentication context = AuthenticationContext.context();
            FdUserCert entity = new FdUserCert();
            entity.setUserId(context.getUserId());
            entity.setDelFlag(YesNoEnum.NO.getCode());
            entity.setCreateTime(new Date());
            BeanUtils.copyProperties(body,entity);
            // 新增
            entity.insert();
            body.setId(entity.getId());
        }else {
            // 主键不为空
            FdUserCert entity = new FdUserCert().selectById(body.getId());
            BeanUtils.copyProperties(body,entity);
            // 更新
            entity.updateById();
        }
        return body;
    }

    /**
     * 删除证书
     */
    @Override
    public Boolean deleteCertificate(Long id) {
        FdUserCert entity = new FdUserCert().selectById(id);
        if(entity == null) {
            throw new ServiceException("证书不存在");
        }
        //entity.setDelFlag(YesNoEnum.YES.getValue());
        return entity.deleteById();
    }

    /**
     * 更新技能
     */
    @Override
    public FdUserSkillDTO updateSkill(FdUserSkillDTO body) {
        if (body.getId() == null){
            // 主键为空
            Authentication context = AuthenticationContext.context();
            FdUserSkill entity = new FdUserSkill();
            entity.setUserId(context.getUserId());
            entity.setDelFlag(YesNoEnum.NO.getCode());
            entity.setCreateTime(new Date());
            BeanUtils.copyProperties(body,entity);
            // 新增
            entity.insert();
            body.setId(entity.getId());
        }else {
            // 主键不为空
            FdUserSkill entity = new FdUserSkill().selectById(body.getId());
            BeanUtils.copyProperties(body,entity);
            // 更新
            entity.updateById();
        }
        return body;
    }

    @Override
    public Boolean deleteSkill(Long id) {
        FdUserSkill entity = new FdUserSkill().selectById(id);
        if(entity == null) {
            throw new ServiceException("技能不存在");
        }
        //entity.setDelFlag(YesNoEnum.YES.getValue());
        return entity.deleteById();
    }

    /**
     * 更新生活照
     */
    @Override
    public Boolean updateLifePhoto(LifePhotoDTO photo) {
        FdUser user = FdUser.getCurrentUser();
        List<String> urls = photo == null ? null : photo.getUrls();
        if(CollectionUtils.isEmpty(urls)) {
            user.setLifePhoto(null);
        } else {
            user.setLifePhoto(String.join(",", urls));
        }
        user.setUpdateTime(new Date());
        return updateById(user);
    }

    @Override
    public FdAuthPersonalVO getPersonalAuthInfo(Long userId) {
        Authentication context = AuthenticationContext.context();
        userId = userId == null ? context.getUserId() : userId;
        FdAuthPersonal entity = new FdAuthPersonal().findOneByUserId(userId);
        if(entity == null) {
            return null;
        }
        FdAuthPersonalVO vo = new FdAuthPersonalVO();
        // 身份证中间脱敏
//        String idNo = entity.getIdNo();
//        if(idNo != null && idNo.length() > 8) {
//            idNo = idNo.substring(0, 4) + "********" + idNo.substring(idNo.length() - 4);
//        }
        BeanUtils.copyProperties(entity, vo);
        //vo.setIdNo(idNo);
        return vo;
    }

    @Override
    public FdAuthEnterpriseVO getEnterpriseAuthInfo(Long userId) {
        Authentication context = AuthenticationContext.context();
        userId = userId == null ? context.getUserId() : userId;
        FdAuthEnterprise entity = new FdAuthEnterprise().findOneByUserId(userId);
        if(entity == null) {
            return null;
        }
        FdAuthEnterpriseVO vo = new FdAuthEnterpriseVO();
        BeanUtils.copyProperties(entity, vo);
        // 营业执照中间脱敏
//        String regNum = entity.getRegNum();
//        if(regNum != null && regNum.length() > 8) {
//            regNum = regNum.substring(0, 4) + "********" + regNum.substring(regNum.length() - 4);
//        }
//        vo.setRegNum(regNum);
        return vo;
    }




    @Override
    public FdUserResumeVO getResume(Long userId) {

        FdUserResumeVO vo = new FdUserResumeVO();
        FdUser user = null;
        if(userId == null) {
            user = FdUser.getCurrentUser();
            userId = user.getId();
        } else {
            user = getById(userId);
            if(user == null) {
                throw new ServiceException("用户不存在");
            }
        }
        // 基本信息
        FdUserInformationDTO info = new FdUserInformationDTO();
        BeanUtils.copyProperties(user, info);

        vo.setInfo(info);

        // 生活照
        if(!StringUtils.isEmpty(user.getLifePhoto())) {
            vo.setLifePhotos(Arrays.asList(user.getLifePhoto().split(",")));
        }

        // 求职意向
        FdJobIntentionsDTO jobIntentions = FdJobIntentions.findOneByUserIdOrDefault(userId);
        vo.setJobIntentions(jobIntentions);

        // 教育经历
        List<FdEduExperienceDTO> eduList = FdEduExperience.findAllByUserId(userId).stream().map(item -> {
            FdEduExperienceDTO edu = new FdEduExperienceDTO();
            BeanUtils.copyProperties(item, edu);
            return edu;
        }).collect(Collectors.toList());
        vo.setEduExperiences(eduList);

        // 工作经历
        List<FdWorkExperience> workList = FdWorkExperience.findByUserId(userId);
        List<FdWorkExperienceDTO> workExperiences = workList.stream().map(item -> {
            FdWorkExperienceDTO work = new FdWorkExperienceDTO();
            BeanUtils.copyProperties(item, work);
            return work;
        }).collect(Collectors.toList());
        vo.setWorkExperiences(workExperiences);

        // 证书
        List<FdUserCert> certList = FdUserCert.findByUserId(userId);
        List<FdUserCertDTO> userCerts = certList.stream().map(item -> {
            FdUserCertDTO cert = new FdUserCertDTO();
            BeanUtils.copyProperties(item, cert);
            return cert;
        }).collect(Collectors.toList());
        vo.setUserCerts(userCerts);

        // 个人技能
        List<FdUserSkill> skillList = FdUserSkill.findByUserId(userId);
        List<FdUserSkillDTO> userSkills = skillList.stream().map(item -> {
            FdUserSkillDTO skill = new FdUserSkillDTO();
            BeanUtils.copyProperties(item, skill);
            return skill;
        }).collect(Collectors.toList());
        vo.setUserSkills(userSkills);

        return vo;
    }




    /**
     * 分页查询
     * @param param 查询条件
     * @return 分页列表
     */
    @Override
    public IPage<FdUserVO> pageList(FdUserSearch param) {
        //查询数据
        IPage<FdUser> page = page(getPage(param), getWrapper(param));
        IPage<FdUserVO> voPage = new Page<>();
        //数据组装
        voPage.setRecords(page.getRecords().stream().map(r->{
            FdUserVO vo = new FdUserVO();
            BeanUtils.copyProperties(r,vo);
            //数据组装
            setViewParam(r,vo);
            return vo;
        }).collect(Collectors.toList()));
        voPage.setPages(page.getPages());
        voPage.setTotal(page.getTotal());
        voPage.setSize(page.getSize());
        voPage.setCurrent(page.getCurrent());
        return voPage;
    }

    /**
     * 动态条件构建
     * @param param 查询参数
     * @return 条件语句
     */
    private LambdaQueryWrapper<FdUser> getWrapper(FdUserSearch param){
        LambdaQueryWrapper<FdUser> wrapper = Wrappers.lambdaQuery();
        // 主键
        wrapper.eq(param.getId() != null, FdUser::getId, param.getId());
        // 关联系统用户
        wrapper.eq(param.getSysUserId() != null, FdUser::getSysUserId, param.getSysUserId());
        // 微信open id
        wrapper.eq(param.getWxId() != null && !param.getWxId().isEmpty(), FdUser::getWxId, param.getWxId());
        // 微信头像url
        wrapper.eq(param.getWxAvatar() != null && !param.getWxAvatar().isEmpty(), FdUser::getWxAvatar, param.getWxAvatar());
        // 微信昵称
        wrapper.eq(param.getWxNickname() != null && !param.getWxNickname().isEmpty(), FdUser::getWxNickname, param.getWxNickname());
        // 用户姓名
        wrapper.eq(param.getName() != null && !param.getName().isEmpty(), FdUser::getName, param.getName());
        // 手机号
        wrapper.eq(param.getPhone() != null && !param.getPhone().isEmpty(), FdUser::getPhone, param.getPhone());
        // 出生年份
        wrapper.eq(param.getBirthYear() != null, FdUser::getBirthYear, param.getBirthYear());
        // 性别:0-男,1-女
        wrapper.eq(param.getGender() != null, FdUser::getGender, param.getGender());
        // 教育状态:0-在读,1-已毕业
        wrapper.eq(param.getEduState() != null, FdUser::getEduState, param.getEduState());
        // 学历:1.初中及以下，2.高中，3.大专，4.本科，5.硕士，6博士及以上
        wrapper.eq(param.getEduLevel() != null, FdUser::getEduLevel, param.getEduLevel());
        // 工作年限:1.无工作经验，2.  0-1年，3.  1-3年，4.  3-5年，5.  5-10年，6.  10年以上
        wrapper.eq(param.getWorkYears() != null, FdUser::getWorkYears, param.getWorkYears());
        // 身高,厘米
        wrapper.eq(param.getHeight() != null, FdUser::getHeight, param.getHeight());
        // 体重,公斤
        wrapper.eq(param.getWeight() != null, FdUser::getWeight, param.getWeight());
        // 自我描述
        wrapper.eq(param.getRemark() != null && !param.getRemark().isEmpty(), FdUser::getRemark, param.getRemark());
        // 邮箱
        wrapper.eq(param.getMail() != null && !param.getMail().isEmpty(), FdUser::getMail, param.getMail());
        // 是否实名认证: 1-已经实名,0-未实名
        wrapper.eq(param.getRealNamed() != null, FdUser::getRealNamed, param.getRealNamed());
        // 是否已个人实名认证: 1-已经实名,0-未实名
        wrapper.eq(param.getPersonalRealNamed() != null, FdUser::getPersonalRealNamed, param.getPersonalRealNamed());
        // 是否已企业实名认证: 1-已经实名,0-未实名
        wrapper.eq(param.getEntRealNamed() != null, FdUser::getEntRealNamed, param.getEntRealNamed());
        // 当前登录身份: 雇工-0,雇主-1
        wrapper.eq(param.getCurrentRole() != null, FdUser::getCurrentRole, param.getCurrentRole());
        // 当前纬度,火星坐标系
        wrapper.eq(param.getCurrentLat() != null, FdUser::getCurrentLat, param.getCurrentLat());
        // 当前经度,火星坐标系
        wrapper.eq(param.getCurrentLon() != null, FdUser::getCurrentLon, param.getCurrentLon());
        // 创建时间
        wrapper.eq(param.getCreateTime() != null, FdUser::getCreateTime, param.getCreateTime());
        // 更新时间
        wrapper.eq(param.getUpdateTime() != null, FdUser::getUpdateTime, param.getUpdateTime());
        // 用户状态,预留
        wrapper.eq(param.getState() != null, FdUser::getState, param.getState());
        //
        wrapper.eq(param.getDelFlag() != null, FdUser::getDelFlag, param.getDelFlag());
        // 主键倒序
        wrapper.orderByDesc(FdUser::getId);
        return wrapper;
    }

    /**
     * 详情
     * @param id 查询条件
     * @return 详情
    */
    @Override
    public FdUserVO info(Long id) {
        // 查询主键详情
        FdUser entity = getById(id);
        if (ObjectUtils.isEmpty(entity)){
            throw new ServiceException("查询不到数据");
        }
        // 回显参数封装
        FdUserVO result = new FdUserVO();
        BeanUtils.copyProperties(entity,result);
        // 数据组装
        setViewParam(entity,result);
        return result;
    }

    /**
     * 新增
     * @param body 参数
     * @return 成功与否
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdate(FdUserDTO body) {
        if (body.getId() == null){
            // 主键为空
            FdUser entity = new FdUser();
            BeanUtils.copyProperties(body,entity);
            // 新增
            return save(entity);
        }else {
            // 主键不为空
            FdUser entity = getById(body.getId());
            BeanUtils.copyProperties(body,entity);
            // 更新
            return updateById(entity);
        }
    }

    /**
     * 批量删除
     * @param idList 主键列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(List<Long> idList) {
        //逻辑删除
        //FdUser entity = new FdUser();
        //entity.setDelFlag(1);
        //return update(entity,new LambdaQueryWrapper<FdUser>().in(FdUser::getId,idList));

        //物理删除
        return removeByIds(idList);
    }



    /**
     * 获取分页对象
     *
     * @param param 分页参数
     */
    protected IPage<FdUser> getPage(FdUserSearch param) {
        return new Page<>(param.getPageNum(), param.getPageSize());
    }

    /**
     * 视图数据赋值
     * @param r 数据
     * @param vo 视图
     */
    private void setViewParam(FdUser r, FdUserVO vo) {
        //数据赋值业务..
    }

}
